<template>
  
  <!--  v-loading="audio.waiting"-->
  <div>
    <audio
        @loadedmetadata="getSongDuration"
        @timeupdate="getCurrentPlaybackPosition"
        @play="onPlay"
        @error="onError"
        @pause="onPause"
        @ended="whenOneSongFinish"
        ref="audio"
        id='audio'
        :src='theUrl'
        :preload='audio.preload'
        autoplay>
    </audio>
    <div class="audio-container">
      <div style="margin: 0 15px 0 15px;display: flex;align-items: center">
        <!--      上一首-->
        <svg class="icon previous_song" aria-hidden="true" @click="previousSong">
          <use xlink:href="#icon-shangyishou"></use>
        </svg>
        <!--      播放或者暂停按钮-->
        <svg class="icon whether_player" aria-hidden="true" @click="startPlayOrPause">
          <use :xlink:href="audio.playing|transPlayPause"></use>
        </svg>
        <!--      下一首-->
        <svg class="icon next_song" aria-hidden="true" @click="nextSong">
          <use xlink:href="#icon-xiayishou1"></use>
        </svg>
      </div>
      <!--      当前歌曲图片-->
      <div style="border-radius: 25px;margin: 0 10px 0 10px;">
        <img v-show="!audio.waiting" style="height: 50px;width: 50px;border-radius: 25px"
             :src="thePicUrl" alt="">
      </div>
      <!--      歌名-->
      <span v-show="!audio.waiting" class="the_song_name">{{ theSongName }}</span>
      <!--      分割符号-->
      <span v-show="!audio.waiting" class="segmentation">--</span>
      <!--      作者-->
      <span v-show="!audio.waiting" class="the_artists">{{ theArtists }}</span>
      <!--      倍速切换按钮-->
      <el-button class="speed" v-show="!controlList.noSpeed" @click="changeSpeed">{{
          audio.speed | transSpeed
        }}
      </el-button>
      <!--      播放进度条-->
      <el-slider class="playback_progress" v-show="!controlList.noProcess" v-model="sliderTime"
                 :format-tooltip="formatProcessToolTip"
                 @change="changeCurrentTime"></el-slider>
      <!--      当前播放进度/歌曲总时长-->
      <el-tag class="max_time" type="info">{{ audio.currentTime | formatSecond }} / {{
          audio.maxTime | formatSecond
        }}
      </el-tag>
      <div
          @mouseenter="controlList.Volume=!controlList.Volume"
          @mouseleave="controlList.Volume=!controlList.Volume"
          class="sound_control">
        <!--      静音按钮-->
        <svg class="icon mute" aria-hidden="true" v-show="!controlList.noMuted" @click="startMutedOrNot">
          <use :xlink:href="audio.muted | transMutedOrNot"></use>
        </svg>
        <!--      音量条-->
        <el-slider
            class="volume_bar"
            vertical
            height="100px"
            v-show="controlList.Volume"
            v-model="volume"
            :format-tooltip="formatVolumeToolTip"
            @change="changeVolume"></el-slider>
      </div>
      <!--      当前播放列表-->
      
      <!--        播放列表-->
      <play-list v-show="controlList.playListTable" @userDeleteOneSong="deleteOneSong"
                 @userDesignatedPlay="designatedPlay" class="playList"></play-list>
      <!--        播放列表按钮-->
      <svg @click="showPlayListTable" class="icon playlistBtn" aria-hidden="true">
        <use xlink:href="#icon-qingdan"></use>
      </svg>
    </div>
  </div>
</template>

<script>
import '@/assets/font/recommend'
import playList from "@/components/playmusic/playList";

function transTime(value) {//格式化时间的全局函数
  let time = '';
  let h = parseInt(`${value / 3600}`);
  value %= 3600;
  let m = parseInt(`${value / 60}`);
  let s = parseInt(`${value % 60}`);
  if (h > 0) {
    time = formatTime(h + ':' + m + ':' + s);
  } else {
    time = formatTime(m + ':' + s);
  }
  return time;
}

// 补零
function formatTime(value) {
  let time = '';
  let s = value.split(':');
  let i = 0;
  for (; i < s.length - 1; i++) {
    time += s[i].length === 1 ? '0' + s[i] : s[i];
    time += ':';
  }
  time += s[i].length === 1 ? '0' + s[i] : s[i];
  return time;
}

let flag = 0//全局变量，指向播放歌单列表的第几首歌曲
export default {
  components: {
    playList,
  },
  name: "playMusic",
  data() {
    return {
      theUrl: '',
      thePicUrl: '',
      theArtists: '',
      theSongName: '',
      thePlayList: this.$store.state.player.playlist,
      Audio: null,//保存audio的dom
      audio: {
        currentTime: 0,//当前播放的时间
        maxTime: 0,//歌曲的总时长，以秒为单位
        playing: false,//播放器是否播放
        muted: false,//播放器是否放音
        speed: 1,//当前快进等级
        waiting: true,//当前歌曲加载状态
        preload: 'auto'
      },
      sliderTime: 0,//进度条的进度百分比
      volume: 100,//当前音量
      speeds: this.theSpeeds,//接收props发送过来的快进等级数组
      controlList: {
        noDownload: false,// 不显示下载
        noMuted: false,// 不显示静音
        Volume: false,// 不显示音量条
        noProcess: false,// 不显示进度条
        onlyOnePlaying: false,// 只能播放一个
        noSpeed: true,// 不要快进按钮
        playListTable: false,//是否显示播放列表
      },
      originalVolume: null//保存用户最后一次的自定义音量
    }
  },
  props: {
    
    theSpeeds: {
      type: Array,
      default() {
        return [1, 1.5, 2]
      }
    },
    theControlList: {
      type: String,
      default: ''
    }
  },
  created() {
    this.bus.$on('userWantPlay', this.beginPlay)
  },
  mounted() {
    this.getElement()
  },
  methods: {
    getElement() {//获取必要的元素
      this.Audio = this.$refs.audio
    },
    IncomingPlaybackElement() {//传入播放所需要的元素
      this.theUrl = this.thePlayList[flag].theUrl
      this.thePicUrl = this.thePlayList[flag].picUrl
      this.theArtists = this.thePlayList[flag].theArtists
      this.theSongName = this.thePlayList[flag].name
    },
    showPlayListTable() {//点击播放列表按钮出现或者隐藏播放列表
      this.controlList.playListTable = !this.controlList.playListTable
    },
    deleteOneSong(index) {//点击播放列表中的删除按钮
      flag = index
      this.IncomingPlaybackElement()
    },
    designatedPlay(index) {//点击播放列表中的播放按钮
      flag = index
      this.IncomingPlaybackElement()
      return this.$message.success('Hi!喜欢这首歌嘛')
    },
    beginPlay() {
      this.IncomingPlaybackElement()
    },
    whenOneSongFinish() {//当当前歌曲播放结束时
      if (this.thePlayList.length - 1 > flag) {//如果后面还有待播歌曲
        flag++//使指针后移一位
        this.IncomingPlaybackElement()
      } else {//如果后面没有歌曲时
        flag = 0//使指针重置为0
        this.IncomingPlaybackElement()
      }
    },
    previousSong() {//用户点击切换上一首歌曲
      if (flag === 0) {
        flag = this.thePlayList.length - 1
        this.IncomingPlaybackElement()
      } else {
        flag--
        this.IncomingPlaybackElement()
      }
    },
    nextSong() {//用户点击切换下一首歌曲
      if (flag === this.thePlayList.length - 1) {
        flag = 0
        this.IncomingPlaybackElement()
      } else {
        flag++
        this.IncomingPlaybackElement()
      }
    },
    startPlayOrPause() {//点击按钮进行播放或者暂停
      return this.audio.playing ? this.pausePlay() : this.startPlay()//检查播放器的播放状态，如果为真则停止播放，如果为假，则开始播放
    },
    pausePlay() {//暂停方法
      this.Audio.pause()
    },
    onPause() {//当歌曲暂停时进行此方法
      this.audio.playing = false//修改播放器状态，为false
    },
    startPlay() {//播放歌曲方法
      this.Audio.play()
    },
    onPlay() {//当歌曲开始播放进行此方法
      this.audio.playing = true//修改播放器当前状态
    },
    changeSpeed() {//更改播放器播放的快进等级
      let index = this.speeds.indexOf(this.audio.speed) + 1//获取当前快进等级在快进等级数组里的位置并加1，为了前进到下一等级快进
      this.audio.speed = this.speeds[index % this.speeds.length]//根据获取到的要前进到的位置来拿取快进值，注意当此时快进等级已经为最高级，加一会超出数组长度，应该回到第一级快进等级，那么余上快进数组的长度即可解决
      this.Audio.playbackRate = this.audio.speed//将我们获取到到快进数组应用到Audio上
    },
    formatProcessToolTip(index = 0) {//index为拖动到的位置百分比
      index = this.audio.maxTime / 100 * index//获取当前拉动到的位置是具体的哪个时间
      return '进度条: ' + transTime(index)//格式化时间
    },
    changeCurrentTime(index) {//当进度条改变时
      this.Audio.currentTime = index / 100 * this.audio.maxTime//更改播放器当前播放进度
    },
    startMutedOrNot() {//用户点击静音或者放音按钮
      this.Audio.muted = !this.Audio.muted//将播放器是否放音反置
      this.audio.muted = this.Audio.muted//将播放器此时的壮态保存到audio.muted
      if (this.audio.muted === true) {
        this.originalVolume = this.volume//将用户最后一次的自定义音量保存到this.originalVolume中
        this.volume = 0//将音量置为0
      } else {
        this.volume = this.originalVolume//将音量恢复到上一次用户自定义的音量值
      }
    },
    changeVolume(index = 0) {
      this.Audio.volume = index / 100//改变播放器音量百分比
      this.volume = index//将此百分比保存到volume中
    },
    
    formatVolumeToolTip(index) {
      if (index !== null) {
        this.Audio.volume = index / 100//改变播放器音量百分比
        this.volume = index//将此百分比保存到volume中
        this.audio.muted = this.volume === 0;
      }
      return '音量条: ' + index
    },
    onError() {//当出现未知当错误时，使播放器进行加载页面
      this.audio.waiting = true
    },
    getSongDuration(res) {//元数据加载完成，获取歌曲总时长
      this.audio.waiting = false//改变audio状态为加载完成
      this.audio.maxTime = parseInt(res.target.duration)//保存歌曲的总时长，以秒为单位
    },
    getCurrentPlaybackPosition(res) {// 当timeupdate事件大概每秒一次，用来更新音频流的当前播放时间
      this.audio.currentTime = res.target.currentTime//将当前播放的时间点保存到audio.currentTime
      this.sliderTime = this.audio.currentTime / this.audio.maxTime * 100//获取当前播放长度占总时长的百分比，保存到this.sliderTime
    },
  },
  filters: {//过滤器
    formatSecond(second = 0) {//过滤当前播放的进度，是用户更容易理解
      return transTime(second)
    },
    transPlayPause(value) {//根据audio.playing来更改暂停播放按钮的显示文字
      return value ? '#icon-zanting' : '#icon-bofang3'
    },
    transMutedOrNot(value) {//根据audio.muted来更改放音或者静音
      return value ? '#icon-jingyin3' : '#icon-yinliang'
    },
    transSpeed(value) {//过滤快进等级数值，使用户更容易理解
      return '快进: x' + value
    },
    
  },
}
</script>

<style scoped lang="less">
.audio-container {
  border-radius: 20px 20px 0 0;
  width: 100%;
  height: 70px;
  background-color: rgba(178, 40, 30, 0.6);
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  
  .previous_song, .next_song {
    font-size: 2em;
    border-radius: 16px;
    border: 2px solid #ffffff;
    padding: 5px;
    color: #AEAEAE;
    transition: all .2s linear;
    
    &:hover {
      color: #ffffff;
      border: 2px solid #AEAEAE;
      box-shadow: 5px 5px 20px #AEAEAE;
      transform: translateY(-2px);
    }
  }
  
  .whether_player { //播放按钮
    font-size: 2.5em;
    border-radius: 24px;
    border: 2px solid #ffffff;
    padding: 5px;
    margin: 10px;
    color: #AEAEAE;
    transition: all .2s linear;
    
    &:hover {
      color: #ffffff;
      border: 2px solid #AEAEAE;
      box-shadow: 5px 5px 20px #AEAEAE;
      transform: translateY(-2px);
    }
  }
  
  //播放速度按钮
  .speed {
  }
  
  
  .the_song_name {
    width: 50px;
    font-size: 12px;
    text-align: center;
    color: #ffffff;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 1;
    -webkit-box-orient: vertical;
  }
  
  .segmentation {
    font-size: 12px;
    color: #ffffff;
    text-align: center;
  }
  
  .the_artists {
    width: 50px;
    font-size: 12px;
    text-align: center;
    color: #ffffff;
    margin-right: 20px;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 1;
    -webkit-box-orient: vertical;
  }
  
  .playback_progress { //播放进度
    width: 200px;
  }
  
  .max_time { //歌曲总时长
    margin: 20px;
  }
  
  .sound_control {
    position: relative;
    
    .mute { //静音按钮
      font-size: 2em;
      border-radius: 24px;
      padding: 5px;
      margin: 10px;
      color: #AEAEAE;
      transition: all .2s linear;
      
      &:hover {
        color: #ffffff;
        box-shadow: 5px 5px 20px #ffffff;
        transform: translateY(-2px);
      }
    }
    
    .volume_bar { //音量条
      position: absolute;
      top: -100px;
      left: 50%;
      transform: translateX(-50%);
    }
  }
  
  .playList {
    position: absolute;
    top: -400px;
    z-index: 9999999999;
  }
  
  .playlistBtn {
    font-size: 2em;
    border-radius: 24px;
    padding: 5px;
    margin: 10px;
    color: #AEAEAE;
    transition: all .2s linear;
    
    &:hover {
      color: #ffffff;
      box-shadow: 5px 5px 20px #ffffff;
      transform: translateY(-2px);
    }
  }
}
/deep/.el-slider__bar{
  background-color: #B2281E!important;
}
/deep/.el-slider__button{
  border:4px solid #B2281E!important;
}
</style>
